package easypsync.app;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.ContactsContract;
import android.util.Log;

public class SyncContacts {
	Context context;

	FileWriter fileWriter;
	
	String outputFilePath;
	
	private final String TAG = SyncContacts.class.getName();

	public SyncContacts(Context context) {
		this.context = context;
	}

	public void sync() {
		openOutputFile();
		AssetFileDescriptor fd;
		try {
			Cursor cursor = context.getContentResolver().query(
					ContactsContract.Contacts.CONTENT_URI,
					null,
					null,
					null,
					null);
			while (cursor.moveToNext()) {
				String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
				Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);

				fd = context.getContentResolver().openAssetFileDescriptor(uri, "r");
				FileInputStream fis = fd.createInputStream();
				byte[] buf = new byte[(int) fd.getDeclaredLength()];
				if (0 < fis.read(buf)) {
					String vCard = new String(buf);
//					if (Log.isLoggable(TAG, Log.DEBUG))
//						Log.d(TAG, vCard);
					writeToOutputFile(vCard);
				}
				fis.close();
			}
			cursor.close();
	
		} catch (FileNotFoundException e) {
			Log.e(TAG, "File not found", e);
			throw new SyncException("Failed", "Failed synching Contacts", "File not found");
		} catch (IOException e) {
			Log.e(TAG, "IO", e);
			throw new SyncException("Failed", "Failed synching Contacts", "IO");
		}

		closeOutputFile();
		transferFile();
	}

	private void openOutputFile() {
		File root = Environment.getExternalStorageDirectory();
//		Log.i(TAG, root.getAbsolutePath());
		if (!root.canWrite()) {
			Log.e(TAG, "CANNOT WRITE");
		}
		File subdir = new File(root, "pimBackup");
		subdir.mkdirs();
		File f = new File(subdir, "contacts.vcs");
		outputFilePath = f.getAbsolutePath();
		try {
			f.createNewFile();
			fileWriter = new FileWriter(f);
		} catch (IOException e) {
			Log.e(TAG, "IO when creating contacts file", e);
		}

		
	}
	
	private void closeOutputFile() {
		try {
			fileWriter.close();
		} catch (IOException e) {
			throw new SyncException("Failed", "Failed synching Contacts", "writer close");
		}
	}
	
	private void writeToOutputFile(String text) {
		try {
			fileWriter.write(text);
		} catch (IOException e) {
			Log.e(TAG, "Could not write to contacts file", e);
		}
	}
	
	private void transferFile() {
		SMBTransfer.transferFile(outputFilePath, "contacts.vcs");
	}
}
